<template>
  <div class="form-parsers form-generator-wrap" :class="{ disabled: disabled }">
    <form-parser
      ref="formParserRef"
      :levelName="levelName"
      v-for="(item, index) in list"
      :key="item._key"
      :type="type"
      :disabled="disabled"
      @change="(data) => onChange(index, data)"
    >
      <template v-slot:card-header>
        <div>{{ item.inspectionItemName || item.itemName }}</div>
        <div class="timer" v-if="item.endTime || item.endTime">
          <span v-if="item.startTime" style="margin-right: 10px"
            >开始时间: {{ item.startTime | formatTime("MM-DD HH:mm") }}</span
          >
          <span v-if="item.endTime"
            >截止时间: {{ item.endTime | formatTime("MM-DD HH:mm") }}</span
          >
        </div>
      </template>
    </form-parser>
  </div>
</template>

<script>
import { deepClone } from "../../utils/index.js";
import { stringify, parse } from "../../utils/json.js";
export default {
  name: "FormParsers",
  props: {
    list: {
      type: Array,
      default: () => [],
    },
    levelName: String,
    type: {
      type: String,
      default: () => "inspection",
    },
    disabled: {
      type: Boolean,
      default: () => false,
    },
  },
  components: {},
  data() {
    return {
      count: Date.now(),
      changeList: [],
    };
  },
  async created() {},
  mounted() {},
  methods: {
    onChange(index, data) {
      // console.log('index', index, 'data', data)
      if (!this.$listeners.change) return;
      try {
        let item = this.list[index];
        let f = this.changeList.find((t) => t.id === item.id);
        if (f) {
          let list = f.list;
          let i = list.findIndex((t) => t.__vModel__ === data.__vModel__);
          if (i > -1) {
            list.splice(i, 1);
          }
          list.push(data);
        } else {
          this.changeList.push({
            id: item.id,
            list: [data],
          });
        }
        let ids = {};
        this.changeList.forEach((t) => {
          ids[t.id] = [];
          t.list.forEach((m) => {
            ids[t.id].push(m.id);
          });
        });
        this.$emit("change", { ids, list: this.changeList });
      } catch (error) {
        console.error(error);
      }
    },
    async validate(isValidate = true) {
      let list = this.$refs.formParserRef.map((t) => t.validate(isValidate));
      let result = await Promise.all(list);
      // console.log(result)
      // 参考接口
      // 执行检查,列表查询：http://172.16.25.106:10086/project/480/interface/api/18566
      // 提交接口:http://172.16.25.106:10086/project/480/interface/api/18527
      // console.log('result', result)
      result = result.map((t, i) => {
        let item = this.list[i];
        let formParserRef = this.$refs.formParserRef[i];
        let result = undefined;
        let reportType = item.reportType + "";
        let standard = undefined;
        let remark = "";
        if (reportType === "1") {
          // console.log('judgement', formParserRef.getComponent('judgement'))
          result = formParserRef.getComponent("judgement").value;
          standard = 1;
        } else if (reportType === "2") {
          // console.log('dataFilling', formParserRef.getComponent('dataFilling'))
          result = formParserRef.getComponent("dataFilling").value;
        } else if (reportType === "3") {
          // console.log('score', formParserRef.getComponent('score'))
          result = formParserRef.getComponent("score").value;
          standard = item.totalScore;
        }
        // 描述备注
        let descriptionRemarks =
          formParserRef.getComponent("descriptionRemarks");
        if (descriptionRemarks) {
          remark = descriptionRemarks.value;
        }
        return {
          ...item,
          id: item.id, //缓存ID
          inspectionItemExecuteResultId: item.inspectionItemExecuteResultId, //任务ID
          userCode: item.userCode, //用户编码
          userName: item.userName, //用户名称
          systemCode: item.systemCode, //系统编码
          systemName: item.systemName, //系统名称
          orgCode: item.orgCode, //组织编码
          orgName: item.orgName, //组织名称
          orgCodePath: item.orgCodePath, //组织编码全路径
          orgNamePath: item.orgNamePath, //组织名称全路径
          result, //填报结果
          resultType: reportType, //结果类型(1-判断，2-数据填报，3-计分)
          standard, //填报标准(计分就保存满分分值，数据填报不存值，判断就保存正常值)
          inspectionItemName: item.inspectionItemName, //巡检项名称
          // 缺字段, inspectionItemId //巡检项ID
          endTime: item.endTime, //结束时间
          moduleDTOS: t.moduleDTOS,
          values: t.values,
          remark, //描述备注
        };
      });
      // console.log('result', result)
      return result;
    },
    showData(scope) {
      console.log("scope", scope);
    },
  },
  watch: {
    list: {
      handler: async function (val, oldVal) {
        val.forEach((t) => {
          if (t._key === undefined) {
            t._key = this.count++;
          }
        });
        await this.$nextTick();
        val.forEach((item, index) => {
          //reportType
          //1-正常/异常
          //2-数据填报
          //3-评分
          // console.log('item', item)
          // 是否是暂存
          let isTemp = false;
          // 是否是逾期
          let isOverdue = false;
          if (
            item.resultTemp &&
            item.resultTemp.moduleDTOS &&
            item.resultTemp.moduleDTOS.length > 0
          ) {
            isTemp = true;
          }
          // console.log("item", item);
          if(item.status === '2'){
            isOverdue = true;
          }
          let modules = deepClone(
            item.resultTemp?.moduleDTOS ||
              item.result.moduleDTOS ||
              item.result.modules
          ); // 优先取缓存数据
          // let firstStard = moudles[0].units.find(t=>t.unitName === '巡检细则')
          const reportTypeFind = modules[0].units.find((item) => {
            return item.unitName === "结果填报方式";
          });
          const r =
            JSON.parse(reportTypeFind.extra).__config__.info.reportType + "";
          let reportType = (item.reportType || r) + "";
          modules[1].units = modules[1].units.filter((m) => {
            // console.log('reportType', reportType, 'unitName', m.unitName, 'totalScore',item.totalScore)
            if (m.unitName === "判断") {
              let result = { __config__: { defaultValue: "1", tip: "" } };
              // 如果没有暂存值
              if (!isTemp) {
                if (this.disabled) {
                  // 当前页面是非编辑状态页面 即：预览页 详情页等
                  if(!m.value || isOverdue){
                    result.__config__.emptyContent = "--";
                  }
                } else {
                  // 当前页面是编辑状态页面 即: 创建页等
                  result.value = "1"; //默认值 正常 为1
                }
              }
            }
            if (m.unitName === "评分") {
              const result = { __config__: { tip: "" } };
              const totalScore = item.totalScore || item.result?.totalScore;
              // console.log('item', item)
              // console.log('totalScore', totalScore)
              let max
              if(totalScore !== undefined || totalScore !== null){
                max = parseInt(totalScore);
                result.__config__.max = max;
                result.max = max;
              }
              //有暂存值 则不做处理 如无暂存值 则判断是编辑页还是非编辑页
              // 非编辑页面 设置为null
              // 编辑页面 设置为最大值
              if (!isTemp) {
                if (this.disabled) {
                  // 当前页面是非编辑状态页面 即：预览页 详情页等
                  if(!m.value || isOverdue) {
                    result.__config__.emptyContent = "--";
                  }
                } else {
                  // 当前页面是编辑状态页面 即: 创建页等
                  if(max){
                    result.value = max;
                  }
                }
              }
            }
            switch (reportType) {
              case "1":
                return !["数据填报", "评分"].includes(m.unitName);
                break;
              case "2":
                return !["判断", "评分"].includes(m.unitName);
                break;
              case "3":
                return !["判断", "数据填报"].includes(m.unitName);
                break;
              default:
                return true;
                break;
            }
          });
          modules.sort((a, b) => parseInt(a.sort) - parseInt(b.sort));
          modules.forEach((t) => {
            t.units.sort((a, b) => parseInt(a.sort) - parseInt(b.sort));
          });
          // console.log('modules', modules)
          this.$refs.formParserRef[index].setModules(modules);
        });
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {},
};
</script>

<style lang="scss" scoped>
.timer {
  margin-top: 5px;
  color: #b9b9b9;
  font-size: 14px;
  font-weight: normal;
}
</style>
<style lang="scss">
.form-parsers.disabled {
  .el-form-item__label {
    color: #989898 !important;
    font-size: 16px !important;
    &:after {
      display: none !important;
    }
  }
  .el-input__inner,
  .el-textarea__inner {
    min-height: auto !important;
    height: auto !important;
    padding-left: 0 !important;
    padding-right: 0 !important;
    background-color: inherit !important;
    border: none !important;
    color: inherit !important;
  }
  .el-radio {
    display: none !important;
    &.is-checked {
      display: inline-block !important;
    }
  }
  .el-radio__input {
    display: none !important;
  }
  .el-radio__label {
    padding-left: 0 !important;
  }
  .el-radio__input.is-disabled + span.el-radio__label {
    color: inherit !important;
  }
}
</style>
